//
//  SecurityMessageEditViewController.m
//  LocomotiveGuards
//
//  Created by xys on 15/11/21.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "SecurityMessageEditViewController.h"
#import "Masonry.h"
#import "SecurityMessageCell.h"
#import "SecurityMessage.h"
#import "PopMsg.h"
#import "SecurityMessageFmdbModel.h"

typedef NS_ENUM(NSInteger, AllSelectButtonStatus)
{
    AllSelect       = 0, //全部选择
    AllCancle       = 1, //全部取消
};

@interface SecurityMessageEditViewController ()

@property (nonatomic,strong) UIButton * allSelectButton;
@property (nonatomic,strong) UIButton * deleteButton;
@property (nonatomic,strong) NSMutableIndexSet * selectedIndexs;
@property (nonatomic,assign) NSInteger selectedCount;//kvo无法监测容器内容的变化

@end

@implementation SecurityMessageEditViewController

- (instancetype)init
{
    if (self = [super init])
    {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(remoteAPNNotificationHandle:) name:@"remoteAPNNotification" object:nil];
    }
    
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.selectedIndexs = [[NSMutableIndexSet alloc]init];
    self.selectedCount = self.selectedIndexs.count;
    [self.rightbtn setTitle:@"取消" forState:UIControlStateNormal];
    
    self.allSelectButton = [[UIButton alloc]init];
    [self.allSelectButton setBackgroundImage:[UIImage imageNamed:@"security_7pic_btn02_on"] forState:UIControlStateNormal];
    [self.allSelectButton setTitle:@"全部选择" forState:UIControlStateNormal];
    self.allSelectButton.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    [self.allSelectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.allSelectButton.tag = AllSelect;
    [self.allSelectButton addTarget:self action:@selector(allSelectButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    self.deleteButton = [[UIButton alloc]init];
    [self.deleteButton setBackgroundImage:[UIImage imageNamed:@"security_7pic_btn03"] forState:UIControlStateNormal];
    [self.deleteButton setTitle:@"删除已选" forState:UIControlStateNormal];
    self.deleteButton.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    [self.deleteButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.deleteButton addTarget:self action:@selector(deleteButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.allSelectButton];
    [self.view addSubview:self.deleteButton];
    self.tableView.allowsSelection = YES;
    self.tableView.allowsMultipleSelection = YES;
    
    /**
     *  KVO 无法监听容器类对象内容的变化,这里使用一个属性去监测期容量的变化
     */
    [self addObserver:self forKeyPath:@"selectedCount" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld  context:nil];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.allSelectButton makeConstraints:^(MASConstraintMaker *make)
    {
        make.left.equalTo(self.view.left);
        make.bottom.equalTo(self.view.bottom);
        make.width.equalTo(SCREEN_WIDTH * 0.5);
        make.height.equalTo(SCREEN_HEIGHT*0.075);
    }];
    
    [self.deleteButton makeConstraints:^(MASConstraintMaker *make)
     {
         make.right.equalTo(self.view.right);
         make.bottom.equalTo(self.view.bottom);
         make.width.equalTo(SCREEN_WIDTH * 0.5);
         make.height.equalTo(SCREEN_HEIGHT*0.075);
     }];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self dismissViewControllerAnimated:NO completion:nil];
}

-(void)remoteAPNNotificationHandle:(NSNotification *) _notification
{
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"selectedCount"];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSNumber * count = [change objectForKey:@"new"];
    if ( count.intValue < self.messageList.count || 0 == self.messageList.count )
    {
        self.allSelectButton.tag = AllSelect;
        [self.allSelectButton setTitle:@"全部选择" forState:(UIControlStateNormal)];
    }
    else
    {
        self.allSelectButton.tag = AllCancle;
        [self.allSelectButton setTitle:@"全部取消" forState:(UIControlStateNormal)];
    }
}

#pragma mark - UITableViewDelegate method -

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*
     获取单元格
     */
    SecurityMessageCell * cell = [tableView dequeueReusableCellWithIdentifier:@"FDFeedCellEdit"];
    if (nil == cell)
    {
        cell = [[SecurityMessageCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"FDFeedCellEdit" hasCheckBox:YES];
    }
    
    SecurityMessage * msg = [SecurityMessage SecurityMessageWithMessageDict:self.messageList[indexPath.row]];
    cell.securityMessage = msg;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if ([self.selectedIndexs containsIndex:indexPath.row])
    {
        cell.selected = YES;
        [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SecurityMessageCell * cell = (SecurityMessageCell * )[tableView cellForRowAtIndexPath:indexPath];
    cell.selected = YES;
    [self.selectedIndexs addIndex:indexPath.row];
    self.selectedCount = self.selectedIndexs.count;//KVO
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SecurityMessageCell * cell = (SecurityMessageCell * )[tableView cellForRowAtIndexPath:indexPath];
    cell.selected = NO;
    [self.selectedIndexs removeIndex:indexPath.row];
    self.selectedCount = self.selectedIndexs.count;//KVO
}

#pragma mark - button clicked handler -

- (void) deleteButtonClicked:(UIButton *) deleteButton
{
    if ( 0 == self.selectedIndexs.count )
    {
        NSLog(@"请选择要删除的消息!");
        [PopMsg showMessage:@"请选择要删除的消息" Lasttime:1];
        return;
    }

    NSMutableArray * msgIdList = [[NSMutableArray alloc]initWithCapacity:self.selectedIndexs.count];
    [self.selectedIndexs enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop)
     {
         NSDictionary * msgDict = [self.messageList objectAtIndex:idx];
         [msgIdList addObject:msgDict[@"msgId"]];
    }];
    
    [self.messageList removeObjectsAtIndexes:self.selectedIndexs];
    [self.tableView reloadData];
    [self.selectedIndexs removeAllIndexes];
    self.selectedCount = self.selectedIndexs.count;
    
    //更新数据库
    SecurityMessageFmdbModel * messageModel = [[SecurityMessageFmdbModel alloc]init];
    [messageModel  deleteMessages:msgIdList];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:SECURITY_MESSAGE_REFRESH_NOTIFICATION object:nil];
    
    /**
     *  返回非编辑界面
     */
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void) allSelectButtonClicked:(UIButton *) allSelectButton
{
    if (AllSelect ==  allSelectButton.tag)
    {
        if (self.messageList.count > 0 )
        {
            [self.selectedIndexs addIndexesInRange:NSMakeRange(0, self.messageList.count)];
            self.selectedCount = self.selectedIndexs.count;//KVO
        }
        [self.tableView reloadData];
    }
    else
    {
        [self.selectedIndexs removeAllIndexes];
        self.selectedCount = self.selectedIndexs.count;//KVO
        [self.tableView reloadData];
    }
}


- (void) goBackButtonClicked:(UIButton *) backButton
{
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void) rigthButtonClicked:(UIButton *) rightButton
{
    [self dismissViewControllerAnimated:NO completion:nil];
}

@end
